//
//  ExtensionController.swift
//  HHSwift
//
//  Created by 华宏 on 2020/8/31.
//  Copyright © 2020 huahong. All rights reserved.
//

import UIKit

class ExtensionController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "扩展"
        
         let num = 8
         num.repeation {
           print("hello")
         }
    }
    

    

}


//MARK:扩展
extension Rectangle{
    
    var center : Point{

        //getter
        get{
            let centerX = origin.x + size.width/2
            let centerY = origin.y + size.height/2
            return Point(x: centerX, y: centerY)
        }

        //setter
        set{
            origin.x = newValue.x - size.width/2
            origin.y = newValue.y - size.height/2
        }
    }
    
    // extension中只能放入convenience的构造函数
    convenience init(center:Point,size:Size){
       let originX = center.x - size.width/2
       let originY = center.y - size.height/2
       self.init(origin: Point(x: originX, y: originY), size: size)
    }
    
    // extension 中放入 Nested Type 嵌套类型
    enum Vertex: Int{
        case LeftTop
        case RightTop
        case RightBottom
        case LeftBottom
    }
    
    func pointAtVertex( v: Vertex ) -> Point{
        
        switch v{
        case .LeftTop:
            return origin
        case .RightTop:
            return Point(x: origin.x + size.width, y: origin.y )
        case .RightBottom:
            return Point(x: origin.x + size.width, y: origin.y + size.height )
        case .LeftBottom:
            return Point(x: origin.x, y: origin.y + size.height )
        }
    }
    
    // extension 中放入 subscript
    subscript(index: Int) -> Point{
        
        assert( index >= 0 && index < 4 , "Index in Rectange Out of Range.")
        
        return pointAtVertex(v: Vertex(rawValue: index)!)      //swift 3
    }
}

extension Int{
    
    func repeation(task:()->Void) {
        for _ in 0..<self {
            task()
        }
    }
}
